<?php
namespace Api\Model;

use Api\Model\BaseModel;
use Common\Util\ConfigUtils;

class WeixinUserModel extends BaseModel {

    private static $instance;

    public static function singleton()
    {
        self::$instance === null and self::$instance = new self();
        return self::$instance;
    }

    public function addOrUpdate($openid, $user)
    {
        // print_r($user['avatarUrl']);
        //头像存储本地
        $generate_avatar = "";
        if (!empty($user['avatarUrl'])) {
            $generate_avatar = $this->generateAvatar($openid, $user['avatarUrl']);
        }
        if ($this->getOneByOpenid($openid)) {
            //更新
            $data = array();
            //$data['openid']=$user['openId'];
            $data['nickname'] = isset($user['nickName']) ? $user['nickName'] : '';
            $data['gender'] = isset($user['gender']) ? $user['gender'] : '';
            $data['city'] = isset($user['city']) ? $user['city'] : '';
            $data['province'] = isset($user['province']) ? $user['province'] : '';
            $data['country'] = isset($user['country']) ? $user['country'] : '';
            $data['avatarurl'] = $generate_avatar;
            $data['originalurl'] = isset($user['avatarUrl']) ? $user['avatarUrl'] : '';
            $data['is_auth'] =1 ;
            //$data['create_time']=date('Y-m-d H:i:s',time);
            $where['openid'] = $openid;
            $this->where($where)->save($data);

        } else {
            //新增
            $data = array();
            $data['openid'] = $openid;
            $data['nickname'] = isset($user['nickName']) ? $user['nickName'] : '';
            $data['gender'] = isset($user['gender']) ? $user['gender'] : '';
            $data['city'] = isset($user['city']) ? $user['city'] : '';
            $data['province'] = isset($user['province']) ? $user['province'] : '';
            $data['country'] = isset($user['country']) ? $user['country'] : '';
            $data['avatarurl'] = $generate_avatar;
            $data['create_time'] = date('Y-m-d H:i:s', time());
            $data['originalurl'] = isset($user['avatarUrl']) ? $user['avatarUrl'] : '';
            $this->add($data);
        }

    }

    public function addUser($openid){
        $data = array();
        if(!$this->getOneByOpenid($openid)){
            $data['openid'] = $openid;
            $data['create_time'] = date('Y-m-d H:i:s', time());
            $this->add($data);
        }
    }


    public function getOneByOpenid($openid){
        $where['openid']=$openid;
        $row = $this->where($where)->find();
        return $row;
    }

    public function getAvatarUrlByOpneid($opnid){
        $where['openid']=$opnid;
        $data=$this->where($where)->field('avatarurl,nickname')->find();
        return $data;
    }

    public function generateAvatar($openid,$avatarUrl)
    {

        $header = array(
            'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0',
            'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
            'Accept-Encoding: gzip, deflate',);
        $url = $avatarUrl;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        $data = curl_exec($curl);
        $return = curl_getinfo($curl, CURLINFO_HTTP_CODE); //我知道HTTPSTAT码哦
        curl_close($curl);

        if ($return != 200) {//把URL格式的图片转成base64_encode格式的！
            ajax_return([
                'result' => 201,
                'msg' => "网络出错,请重试"
            ]);
        }

        $imgBase64Code = "data:image/jpeg;base64," . base64_encode($data);
        $img_content = $imgBase64Code;//图片内容
        //echo $img_content;exit;
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $img_content, $result)) {
            $type = $result[2];//得到图片类型png?jpg?gif?
            $image_path='./Upload/'.$openid.".".$type;

            if (file_put_contents($image_path, base64_decode(str_replace($result[1], '', $img_content)))) {
                //echo '新文件保存成功：', $image_path;
                $url = ConfigUtils::getConfig('SERVER_URL');
                return $url.$image_path;
            }
            ajax_return([
                'result' => 201,
                'msg' => "网络出错,请重试"
            ]);
        }


    }
}
